import { useState, useRef, useContext, useEffect } from 'react';
import { Popover, Grid, Toast, Popup } from 'antd-mobile';
import { DownCircleOutline, SendOutline, MessageOutline, UpCircleOutline } from 'antd-mobile-icons';
import {
  CopyOutlined,
  HistoryOutlined,
  RollbackOutlined,
  CheckSquareOutlined,
  FileAddOutlined,
  DeleteOutlined,
  ThunderboltOutlined,
} from '@ant-design/icons';
import copy from 'copy-text-to-clipboard';
import { useHistory } from 'react-router-dom';
import moment from 'moment';

import SelectContractor from '../SelectContractor';
import Collection from '../Collection';

import { defaultEnableOperate, MessageTypeCanOperate } from './config';
import { ContentType, ConversationType } from '../../constants';
import { MySdkStoreContext } from '../../context';

import './style.scss';

// 根据强提醒消息类型，渲染内容
const resolveStrongReminderContent = (msgType, content) => {
  switch(msgType) {
    case ContentType.Text:
      return content.text;
    case ContentType.Image:
      return content.pic;
    case ContentType.Face:
      return content.emoji;
    case ContentType.Voice:
      return content.url;
    case ContentType.File:
      return content.url;
    default:
      return msgType;
  }
}

export default function(props) {
  const history = useHistory();
  const mySdkStore = useContext(MySdkStoreContext);
  const messageOperationRef = useRef(null);
  const { userName: myUserName, userId: myUserId } = mySdkStore.mockConfig;
  const { popoverVisible, onMultiSelect, onReply, onLater, onRecall, onDelete, onAddEmojiReply, onPopoverClose, messageData, converInfo } = props;
  const { cid, msgId, localMsgId, msgContent, msgType } = messageData;
  const { sessionName, subUserId } = converInfo;
  // 是否展示”选择联系人“界面开关
  const [selectContractorVisible, setSelectContractorVisible] = useState(false);
  // 是否展示”选择标签“界面开关
  const [collectionVisible, setCollectionVisible] = useState(false);
  // 是否展示”emoji表情“区域开关
  const [emojiListVisible, setEmojiListVisible] = useState(false);
  // 判断是否是本人发送的消息
  const isSendBySelf = myUserId === messageData.from?.userId;
  // 根据消息类型判断是否可操作按钮的config配置信息
  const messageTypeCanOperateConfig = { ...defaultEnableOperate, ...MessageTypeCanOperate[msgType] };
  // emoji表情列表
  const [emojiList, setEmojiList] = useState(mySdkStore.emojiList || []);

  useEffect(() => {
    if (!emojiList?.length) {
      mySdkStore.sdk.getEmojiById("all").then(data => setEmojiList(data));
    }
  }, []);

  // 关闭整个组件显示区域
  const closePopover = () => {
    onPopoverClose();
    // 取消长按事件带来的默认选中区域
    window.getSelection()?.removeAllRanges();
  }

  // 点击”转发“按钮事件，展示”选择联系人“界面
  const handleTransfer = () => {
    setSelectContractorVisible(true);
    closePopover();
  }

  // 点击”提醒“按钮事件，发送一条新的提醒消息
  const handleDing = async() => {
    const msgBody = {
      msgType: ContentType.StrongReminder,
      msgContent: {
        type: 0,
        receiversList: [subUserId],
        sourceCid: cid,
        sourceCname: sessionName,
        sourceMsgId: msgId,
        sourceContentType: msgType,
        sourceMessageContent: msgContent,
        content: resolveStrongReminderContent(msgType, msgContent),
        attachmentList: [],
        isTimed: false,
        scheduleSendTime: '',
        isSeparateSend: true,
        notifyInterval: 0,
        sendBySourceSession: true,
        sendNewMsgToSession: true,
        isSendBySingleSession: false,
      }
    };
    // const msgParams = mySdkStore.sdk.messageBuilder(msgBody);
    try {
      const sendSesData = await mySdkStore.sdk.sendStrongReminderMessage({ content: msgBody.msgContent });
      closePopover();
    } catch (e) {
      // @ts-ignore
      Toast.show(e.errorMessage || e.message);
    }
  }

  // 选择完联系人后，处理转发
  const handleSelectOk = async (selectedItem) => {
    await mySdkStore.sdk.transferMessages({ msgIds: [{ msgId }], originalCid: cid, toCids: selectedItem });
    if (selectedItem.length === 1) {
      Toast.show('转发成功');
      history.push({ pathname: `/chatDetail/${selectedItem[0]?.cid}`});
      setSelectContractorVisible(false);
    } else {
      Toast.show('转发成功');
      // history.push({ pathname: `/chatDetail/${selectedItem[0]?.cid}`});
      setSelectContractorVisible(false);
    }
    closePopover();
  }

  // 点击”回复“按钮后，处理回复事件
  const handleReply = () => {
    onReply({ ...messageData, visible: true });
    closePopover();
  }

  // 点击”复制“按钮事件
  const handleCopy = () => {
    copy(msgContent.text);
    Toast.show('文本复制成功');
    closePopover();
  }

  // 点击”收藏“按钮，展示”选择标签”界面
  const handleCollect = () => {
    setCollectionVisible(true);
    closePopover();
  }

  // 选择收藏标签后，处理收藏事件
  const handleCollectionOk = async (tagCodes) => {
    try {
      mySdkStore.sdk.collectMessage({ cid, messageId: msgId, tagCodes });
      Toast.show('收藏成功');
      setCollectionVisible(false);
      closePopover();
    } catch(e) {
      console.log(e);
    }
  }

  // 点击”稍后处理“按钮
  const handleLater = async () => {
    await mySdkStore.sdk.changeMessagesStatus({ type: 'later', msgIds: [{ msgId, localMsgId }], cid });
    Toast.show('已加入稍后处理列表');
    onLater(messageData);
    closePopover();
  }

  // 点击”撤回“按钮
  const handleRecall = async () => {
    await mySdkStore.sdk.changeMessagesStatus({ type: 'recall', msgIds: [{ msgId, localMsgId }], cid }).then(data => {
      console.log('撤回受理', data);
    });
    onRecall(messageData);
    closePopover();
  }

  // 点击”删除“按钮
  const handleDelete = async () => {
    await mySdkStore.sdk.changeMessagesStatus({ type: 'delete', msgIds: [{ msgId, localMsgId }], cid })
    onDelete(messageData);
    closePopover();
  }

  // 选中单个emoji后，处理发送emoji消息
  const handleSendEmoji = async (emojiData) => {
    const { globalUniqueId: iconId, cn: emoji, url } = emojiData;
    await mySdkStore.sdk.addFaceReplyToMsg({ iconId, emoji, messageId: msgId});
    const instantReplyFaceInfo = {
      faceContent: { iconId, iconUrl: url },
      from: { name: myUserName, userId: myUserId },
    }
    onAddEmojiReply({ ...messageData, instantReplyFaceInfo: instantReplyFaceInfo });
    closePopover();
  }

  // 控制emoji区域展示开关
  const handleEmojiListVisible = () => {
    setEmojiListVisible(!emojiListVisible);
  }

  const popUpContent = <div className="">
    { messageTypeCanOperateConfig.canEmoji &&
    <>
    <div className="emoBar">
      {/* 常用emoji快捷回复区域 */}
        <Grid columns={6} style={{ '--justify-content': 'space-between', textAlign: 'center' }}>
          {emojiList.filter((_, index) => index < 5).map(emoji => <Grid.Item key={emoji.url}>
            <img
              src={emoji.url}
              onClick={() => handleSendEmoji({ ...emoji })}
              alt="emoji"
              style={{width: '24px', height: '24px', padding: '0 4px' }
            }/>
            </Grid.Item>)}
          <Grid.Item onClick={handleEmojiListVisible}>
            { emojiListVisible ? <UpCircleOutline style={{ fontSize: 24 }} /> :
              <DownCircleOutline style={{ fontSize: 24 }} />
            }
          </Grid.Item>
        </Grid>
    </div>
    {/* 完整的emoji区域 */}
    {emojiListVisible &&
      <div className="emojiListSection">
        <Grid columns={6} style={{ '--justify-content': 'space-between', '--gap-vertical': '4px', textAlign: 'center' }}>
          {mySdkStore.emojiList.map(emoji => <Grid.Item key={emoji.url}>
            <img
              src={emoji.url}
              onClick={() => handleSendEmoji(emoji)}
              alt="emoji"
              style={{width: '24px', height: '24px', padding: '0 4px' }
            }/>
            </Grid.Item>)}
        </Grid>
      </div>
    }
    </>
    }
    <div className="operatorSection">
      <Grid columns={6} wrap style={{ '--gap': '12px' }}>
        {/* 配置信息中可以钉的消息类型，并且由我发送，并且是单聊聊天窗则展示该按钮 */}
        { messageTypeCanOperateConfig.canStrongReminder && isSendBySelf && converInfo.type === ConversationType.Single && !mySdkStore.isHideSomeFunctions &&
        <Grid.Item key="strongRemind">
          <div className="iconBtn" onClick={handleDing}>
            <ThunderboltOutlined /> <div className="iconText">提醒</div>
          </div>
        </Grid.Item>
        }
        {/* 配置信息中可以复制的消息类型，并且消息类型为文本消息，则展示该按钮 */}
        { messageTypeCanOperateConfig.canCopy && messageData.msgType === ContentType.Text &&
        <Grid.Item key="copy">
          <div className="iconBtn" onClick={handleCopy}>
            <CopyOutlined /> <div className="iconText">复制</div>
          </div>
        </Grid.Item>
        }
        {/* 配置信息中可以转发的消息类型则展示该按钮 */}
        { messageTypeCanOperateConfig.canTransfer &&
        <Grid.Item key="transfer">
        <div className="iconBtn" onClick={handleTransfer}>
          <SendOutline /> <div className="iconText">转发</div>
        </div>
        </Grid.Item>
        }
        {/* 配置信息中可以回复的消息类型，并且不是本人发送的钉消息则展示该按钮 */}
        { messageTypeCanOperateConfig.canReply && !(messageData.msgType === ContentType.StrongReminder && isSendBySelf) &&
        <Grid.Item key="reply">
        <div className="iconBtn" onClick={handleReply}>
          <MessageOutline /> <div className="iconText">回复</div>
        </div>
        </Grid.Item>
        }
        {/* 配置信息中可以收藏的消息类型则展示该按钮 */}
        { messageTypeCanOperateConfig.canCollect && !mySdkStore.isHideSomeFunctions &&
        <Grid.Item key="collect">
        <div className="iconBtn" onClick={handleCollect}>
          <FileAddOutlined /> <div className="iconText">收藏</div>
        </div>
        </Grid.Item>
        }
        {/* 配置信息中可以稍后处理的消息类型则展示该按钮 */}
        { messageTypeCanOperateConfig.canLater && !isSendBySelf &&
        <Grid.Item key="later">
        <div className="iconBtn" onClick={handleLater}>
          <HistoryOutlined /> <div className="iconText">稍后处理</div>
        </div>
        </Grid.Item>
        }
        {/* 配置信息中可以撤回的消息类型，并且本人发送，发送时间为30分钟以内的消息，则展示该按钮 */}
        { messageTypeCanOperateConfig.canRecall && isSendBySelf && moment().diff(messageData.timestamp, 'minutes') < 30 &&
        <Grid.Item key="recall">
        <div className="iconBtn" onClick={handleRecall}>
          <RollbackOutlined /> <div className="iconText">撤回</div>
        </div>
        </Grid.Item>
        }
        {/* 配置信息中可以多选的消息类型则展示该按钮 */}
        { messageTypeCanOperateConfig.canMultiSelect &&
        <Grid.Item key="multiSelect">
        <div className="iconBtn" onClick={ () => { onMultiSelect(msgId); closePopover(); } }>
          <CheckSquareOutlined /> <div className="iconText">多选</div>
        </div>
        </Grid.Item>
        }
        {/* { messageTypeCanOperateConfig.canSecretSend && isSendBySelf &&
        <Grid.Item key="secretSend">
        <div className="iconBtn">
          <LockOutlined /> <div className="iconText">私发</div>
        </div>
        </Grid.Item>
        } */}
      {/* { messageTypeCanOperateConfig.canStayTop &&
        <Grid.Item key="stayTop">
        <div className="iconBtn">
          <LockOutlined /> <div className="iconText">置顶</div>
        </div>
        </Grid.Item>
        } */}
        {/* 配置信息中可以删除的消息类型则展示该按钮 */}
        { messageTypeCanOperateConfig.canDelete &&
        <Grid.Item key="delete">
        <div className="iconBtn" onClick={handleDelete}>
          <DeleteOutlined /> <div className="iconText">删除</div>
        </div>
        </Grid.Item>
        }
      </Grid>
    </div>
  </div>
  return <>
      <Popover
        visible={popoverVisible}
        ref={messageOperationRef}
        className="messageOperationsComponent"
        content={popUpContent}
        mode="dark"
        placement="bottom-start"
        >
      {props.children}
    </Popover>
    { selectContractorVisible && <SelectContractor onOk={handleSelectOk} onClose={() => setSelectContractorVisible(false)} /> }
    <Popup visible={collectionVisible} bodyClassName="selectorOperationsBarComponnet-collectionPopup">
      <Collection onClose={() => setCollectionVisible(false)} onOk={handleCollectionOk} />
    </Popup>
  </>
}